#!/usr/bin/env node

const http = require('http'),
      cheerio = require('cheerio'),
      fs = require('fs');

http.createServer((req, res) => {
  fs.readFile('./news.html', (err, data) => {
    if(data) {
      const content = data.toString('utf8');
      const $ = cheerio.load(content);
      let dataList = [];
    $('.model-details .news-model').each((index, element) => {
      let createTime = $(element).children('span').text();
      let title = $(element).children('a').children('b').text();
      let createYear = createTime.slice(1,5);
      let time = createTime.slice(1,-1);
      if (createYear === '2018') {
        const newsData = {
          newsTitle: title,
          createTime: time
        }
        dataList.push(newsData);
      }
    });
    /*
    res.end(`<!DOCTYPE html>\n` +
      `<html lang="en"\n` +
      `<head><meta charset="UTF-8"></head>\n` +
      `<body>${JSON.stringify(dataList)}</body></html>`);*/
    res.setHeader('Content-Type','text/plain;charset=utf-8'); 
    res.write(`${JSON.stringify(dataList)}`);
    res.end();
    }
  });
}).listen(8081);
